# 给你一个正整数 n ，生成一个包含 1 到 n² 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
#
#  示例 1：
# 输入：n = 3
# 输出：[[1,2,3],[8,9,4],[7,6,5]]
#
#
#  示例 2：
# 输入：n = 1
# 输出：[[1]]
#
#
#  Related Topics 数组 矩阵 模拟 👍 1275 👎 0
from typing import List


class Solution:
    def generateMatrix2(self, n):
        """
        模拟写法二
        """
        if n <= 0:
            return []

        # 初始化 n x n 矩阵
        matrix = [[0] * n for _ in range(n)]

        # 初始化边界和起始值
        top, bottom, left, right = 0, n - 1, 0, n - 1
        num = 1

        while top <= bottom and left <= right:
            # 从左到右填充上边界
            for i in range(left, right + 1):
                matrix[top][i] = num
                num += 1
            top += 1

            # 从上到下填充右边界
            for i in range(top, bottom + 1):
                matrix[i][right] = num
                num += 1
            right -= 1

            # 从右到左填充下边界

            for i in range(right, left - 1, -1):
                matrix[bottom][i] = num
                num += 1
            bottom -= 1

            # 从下到上填充左边界

            for i in range(bottom, top - 1, -1):
                matrix[i][left] = num
                num += 1
            left += 1

        return matrix

    def generateMatrix1(self, n: int) -> List[List[int]]:
        """
        完全模拟
        每次填充一圈分为（四个方向都遵从左闭右开）：
            从左到右
            从上到下
            从右到左
            从下到上
        """
        if n <= 0:
            return []
        matrix = [[0] * n for i in range(n)]
        loop_count = n // 2
        if n % 2 != 0:  # n 为奇数，那么中心点有值，否则没有中心点
            matrix[n // 2][n // 2] = n * n
        start_x, start_y = 0, 0  # 每一层的循环开始点
        current_num = 1

        for layer in range(1, loop_count + 1):  # 控制每层的循环
            for j in range(start_x, n - layer):  # 从左到右
                matrix[start_x][j] = current_num
                current_num += 1
            for i in range(start_x, n - layer):  # 从上到下
                matrix[i][n - layer] = current_num
                current_num += 1
            for j in range(n - layer, start_x, -1):  # 从右到左
                matrix[n - layer][j] = current_num
                current_num += 1
            for i in range(n - layer, start_y, -1):  # 从下到上
                matrix[i][start_y] = current_num
                current_num += 1
            start_x += 1
            start_y += 1

        return matrix

    def generateMatrix(self, n):
        return self.generateMatrix2(n)


# test code
if __name__ == "__main__":
    n = 3
    print(Solution().generateMatrix(n))
